package com.changpay.zywy.ui.activity.main

import android.content.Intent
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.TextView
import com.changpay.zywy.R
import com.changpay.zywy.base.BaseActivity
import com.changpay.zywy.base.IView
import com.changpay.zywy.bean.BankCardBean
import com.changpay.zywy.constant.Constant
import com.changpay.zywy.ext.showToast
import com.changpay.zywy.ext.sss
import com.changpay.zywy.http.RetrofitHelper
import com.changpay.zywy.ui.activity.mine.BankCardActivity
import com.changpay.zywy.ui.activity.mine.PayPasswordActivity
import com.changpay.zywy.ui.dialog.InputCodeDialog
import com.changpay.zywy.ui.dialog.InputPasswordDialog
import com.changpay.zywy.utils.*
import kotlinx.android.synthetic.main.activity_ti_xian.*
import kotlinx.android.synthetic.main.title_layout.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.util.*


class TiXianActivity : BaseActivity(), IView, MoneyTextWatcher.CountAccountAndChargeInterface {


    var balance = 0f
    var yu_er = ""
    var wallet_type = "1"
    private var bankCardBean: BankCardBean? = null
    private var card_id: String? = null
    private var pd_cash_service_charge = "0"
    private var single_pd_cash_price = "0"
    private var code = ""

    var member_mobile: String by Preference(Constant.MEMBER_MOBILE, "")

    private var dialogClickListener: InputPasswordDialog.OnDialogClickListener? = null
    private var dialogCodeListener: InputCodeDialog.OnDialogClickListener? = null
    override fun attachLayoutRes(): Int {
        return R.layout.activity_ti_xian
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    override fun showDefaultMsg(msg: String) {
        showToast(msg)
    }

    override fun showMsg(msg: String) {
        showToast(msg)
    }

    override fun showError(errorMsg: String) {
        showToast(errorMsg)
    }


    override fun initData() {
    }

    override fun initView() {
        iv_back.onClick { finish() }
        tv_title.text = "提现"
        yu_er = intent.getStringExtra("yu_er")
        wallet_type = intent.getStringExtra("wallet_type")
        tv_balance.text = "余额 ¥ $yu_er"
        balance = yu_er.toFloat()
        initTiXianListener()

        dialogClickListener = InputPasswordDialog.OnDialogClickListener { type ->
            ConfirmMoneyTwo(type)
        }

        dialogCodeListener = object : InputCodeDialog.OnDialogClickListener {
            override fun onClick(type: String?) {
                code = type!!
                val builder = InputPasswordDialog.Builder(this@TiXianActivity)
                val money = et_money.text.toString()
                builder.setMoney("￥ $money").setOnDialogClickListener(dialogClickListener)
                val build = builder.build<InputPasswordDialog>()
                build.show(supportFragmentManager)
            }
            override fun getSMSCode(view: View?,message:View?,success:View?) {
                // 请求
                val param = hashMapOf<String, String>()
                param["key"] = token
                param["phone"] = member_mobile
                param["type"] = "10"
                RetrofitHelper.service.get_sms_captcha(param).sss(this@TiXianActivity)
                {
                    starCode(view as TextView)
                    message?.visibility = View.VISIBLE
                    success?.visibility = View.VISIBLE
                }
            }
        }

    }


    fun starCode(mTimer : TextView) {
        val test = this
        object : CountDownTimer(60000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                if (test.isFinishing) {
                    this.cancel()
                    return
                }
                mTimer.isEnabled = false
                mTimer.text = (millisUntilFinished / 1000).toString() + "s"
            }

            override fun onFinish() {
                if (test.isFinishing) {
                    this.cancel()
                    return
                }
                mTimer.isEnabled = true
                mTimer.text = "重新获取"
            }
        }.start()
    }

    override fun start() {
        loadView()
        loadSettingInfo()

    }

    /**
     * 加载银行卡数据
     */
    private fun loadView() {

        val param = hashMapOf<String, String>()
        param["key"] = token
        RetrofitHelper.service.get_member_bank(param).sss(this) {
            val data_one = it.result
            val bankCardBean = data_one[0]
            var bank_card = bankCardBean.bank_card!!
            bank_card = bank_card.substring(bank_card.length -4, bank_card.length )
            tv_bank_card_name.text = bankCardBean.bank_name + " (" + bank_card + ")"
            card_id = bankCardBean.card_id.toString()
        }
    }

    private fun loadSettingInfo() {
        val params = HashMap<String, String>()
        params["key"] = token
        RetrofitHelper.service.get_pd_cash_setting_info(params).sss(this)
        {
            pd_cash_service_charge =
                GsonUtils.getStringFromJSON(it.result.toString(), "pd_cash_service_charge").toString()
            single_pd_cash_price = GsonUtils.getStringFromJSON(it.result.toString(), "single_pd_cash_price")!!
        }
    }

    private fun initTiXianListener() {
        tv_quan_bu_ti_xian.setOnClickListener { et_money.setText(yu_er) }

        rl_bank_card.setOnClickListener {
            val intent = Intent(this, BankCardActivity::class.java)
            intent.putExtra("type", 1)
            startActivityForResult(intent, 100)
        }
        bt_ti_xian.setOnClickListener { submit() }
        iv_back.setOnClickListener { finish() }
        //默认两位小数
        et_money.addTextChangedListener(MoneyTextWatcher(et_money, this))
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == 200) {
            val infoString = data?.getStringExtra("info")
            bankCardBean = GsonUtils.jsonToBean(infoString!!, BankCardBean::class.java)
            // 选中第一个银行卡
            var bank_card = bankCardBean?.bank_card
            bank_card = bank_card?.substring(bank_card.length - 4, bank_card.length)
            tv_bank_card_name.text = bankCardBean?.bank_name + " (" + bank_card + ")"
            card_id = bankCardBean?.card_id.toString()
        }
    }

    /**
     * 提交银行卡数据
     */
    private fun submit() {
        InputMethodUtils.hideSoftInput(this)
        val money = et_money.text.toString()
        val empty = TextUtils.isEmpty(money)
        if (empty) {
            showToast("请先输入提现金额")
            return
        }
        ConfirmMoneyOne()
    }


    private fun ConfirmMoneyOne() {
        val builder = InputCodeDialog.Builder(this@TiXianActivity)
        builder.setOnDialogClickListener(dialogCodeListener)
        val build = builder.build<InputCodeDialog>()
        build.show(supportFragmentManager)
    }

    private fun ConfirmMoneyTwo(password:String) {
        val params = HashMap<String, String>()
        params["pdc_amount"] = et_money.text.toString()
        params["card_id"] = card_id.toString()
        params["password"] = password
        params["key"] = token
        params["wallet_type"] = wallet_type
        params["captcha"] = code
        RetrofitHelper.service.pd_cash_add(params).sss(this)
        {
            showToast(it.result.toString())
            finish()
        }
    }

    override fun afterTextChang(s: String) = if (TextUtils.isEmpty(s)) {
        ll_quan_bu_ti_xian.visibility = View.VISIBLE
        ll_shou_xun_fei.visibility = View.GONE
    } else {
        ll_quan_bu_ti_xian.visibility = View.GONE
        ll_shou_xun_fei.visibility = View.VISIBLE
        val percentage = java.lang.Double.valueOf(pd_cash_service_charge)
        val monye = java.lang.Double.valueOf(s)
        val c = monye * percentage
        val cc1 = StringUtil.calculateProfit(c)
        val aDouble = java.lang.Double.valueOf(cc1)
        Log.e("songwang", "afterTextChang: $c")
        val text = StringBuilder()
        if (c > 0) {
            text.append("扣除 ¥ " + cc1 + "服务费")
        }
        val charge = java.lang.Double.valueOf(single_pd_cash_price)
        if (charge > 0) {
            text.append(" 手续费 ¥ " + StringUtil.calculateProfit(charge))
        }
        val v = monye - aDouble - charge
        if (v > 0) {
            text.append(" 实际到账金额 ¥ " + StringUtil.calculateProfit(v))
        }
        tv_account_money.setText(text.toString())
    }

}

